package com.katze.boot.plugins.shiro.framework;

import com.katze.boot.plugins.shiro.annotations.RestRequestMapping;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;

import java.lang.annotation.Annotation;

/**
 * 说  明：shiro权限注解的检验
 * 作  者：zf.zeng
 * 日  期：2020-04-04 (星期六)
 **/
public class RequestPermissionAnnotationHandler extends AuthorizingAnnotationHandler {

    public RequestPermissionAnnotationHandler() {
        super(RestRequestMapping.class);
    }

    @Override
    public void assertAuthorized(Annotation a) throws AuthorizationException {
        if (a instanceof RestRequestMapping) {
            RestRequestMapping rpAnnotation = (RestRequestMapping) a;
            String[] permits = rpAnnotation.permits();
            if (permits.length == 1) {
                if (permits[0].equals("")) return;
                this.getSubject().checkPermission(permits[0]);
            } else if (Logical.AND.equals(rpAnnotation.logical())) {
                this.getSubject().checkPermissions(permits);
            } else if (Logical.OR.equals(rpAnnotation.logical())) {
                boolean hasAtLeastOnePermission = false;
                for (String permission : permits) {
                    if (this.getSubject().isPermitted(permission)) hasAtLeastOnePermission = true;
                }
                if (!hasAtLeastOnePermission) {
                    this.getSubject().checkPermission(permits[0]);
                }

            }
        }
    }

}
